const Koa = require("koa");
const http = require("http");
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const koajwt = require("koa-jwt");
const util = require("./utils/utils");
const myLog = require("../src/utils/myLog");
const cors = require("koa2-cors");
const index = require("./routes/index");
const users = require("./routes/users");
const app = new Koa();
const server = http.createServer(app.callback());
const io = require("socket.io")(server, {
  allowEIO3: true,
  cors: {
    origin: "*", // from the screenshot you provided
    methods: ["GET", "POST"],
  },
});
const chats = require("./routes/chats");
const medicalRecords = require("./routes/medicalRecord");

io.on("connection", (socket) => {
  socket.on("sendPrivateMsg", (data) => {
    socket.broadcast.emit("getPrivateMsg", data);
    socket.emit("getPrivateMsg", data);
  });
  socket.on("sendGroupChat", (data) => {
    socket.broadcast.emit("getGroupMsg", data);
    socket.emit("getGroupMsg", data);
  });
});

// error handler
onerror(app);

// 配置跨域
app.use(
  cors({
    originL: "*",
  })
);

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
app.use(require("koa-static")(__dirname + "/public"));

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

// logger
app.use(async (ctx, next) => {
  switch (ctx.method.toLowerCase()) {
    case "get":
      myLog.info("get 请求, params:" + JSON.stringify(ctx.request.query));
      break;
    case "post":
      myLog.info("post 请求, params:" + JSON.stringify(ctx.request.body));
      break;
  }
  await next().catch((err) => {
    // 如果状态码是401
    if (err.status === 401) {
      ctx.status = 200;
      ctx.body = util.fail("token 验证失败", util.CODE.AUTH_ERROR);
    }
  });
});

app.use(
  koajwt({ secret: "yydy" }).unless({
    // 不校验的url,格式是正则
    path: [/^\/users\/login/, /^\/users\/register/, /^\/users\/forgetPsd/],
  })
);

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(medicalRecords.routes(), medicalRecords.allowedMethods());
app.use(chats.routes(), chats.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = server;
